<template>
  <vab-card
    shadow="always"
    v-loading="loading"
    element-loading-background="rgba(122, 122, 122, 0.6)"
  >
    <!-- <template #header class="products_font1">产品价格明细</template> -->
    <template #header>
      <div class="flex_sb">
        <div class="leve2_title flex">产品价格明细 
          <span class="pour_text flex">注： <sapn class="required_text">*</sapn> 为必填项</span>
        </div>
        <div class="flex">
          <el-button
            size="small"
            class="button_update"
            @click="handleProduct('add')"
          >
            新增产品
          </el-button>
          <!-- <el-button
            size="small"
            class="button_update"
            @click="handleProduct('priceUpdate')"
          >
            价格更新
          </el-button> -->
          <el-button
            size="small"
            class="button_update"
            @click="handleProduct('stop')"
          >
            产品停用
          </el-button>
          <!-- <el-button
            size="small"
            class="button_update"
            @click="handleProduct('start')"
          >
            重新启用
          </el-button> -->
        </div>
      </div>
    </template>
    <div :class="{ 'warn': isWarn }">
      <el-form
        :ref="(el) => (productFormRef = el)"
        :model="productList"
        class="formData"
        :rules="rules"
      >
        <el-table
          border
          height="300px"
          :data="productList"
          v-loading="tableLoading"
          @selection-change="handleCurrentChange"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="selection" width="55" :selectable="selectable"/>
          <el-table-column label="序号" align="center" width="60">
            <template #default="props">
              {{ props.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="goods_no" align="center" min-width="200">
            <template #header>
              <span class="required_text">*</span>
              <span>产品编码</span>
            </template>
            <template #default="props">
              <el-form-item prop="number">
                <LazySelect :ref="(el) => lazySelectNumberRef = el" :userOrgId="userOrgId" :disabled="props.row.productDisabled" :clearable="false" v-model:value="props.row.number" type="number" @LazyChange="(value) => {
                  productQuerySearch(value, 'number', props.$index, 'number')
                }"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goods_name" align="center" min-width="300">
            <template #header>
              <span class="required_text">*</span>
              <span>产品名称</span>
            </template>
            <template #default="props">
              <el-form-item prop="name">
                <LazySelect :userOrgId="userOrgId" :disabled="props.row.productDisabled" :clearable="false"  v-model="props.row.name" type="" @LazyChange="(value) => {
                  productQuerySearch(props.row.name, 'number', props.$index, 'name')
                }"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="specification" align="center" width="100">
            <template #header>
              <span>规格型号</span>
            </template>
            <template #default="props">
              <span
                class="ellipsis"
                v-text="_FieldFormat(props.row.specification)"
              ></span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="batch_no"
            label="批次号"
            align="center"
            width="150"
          >
            <template #default="props">
              <el-form-item prop="batch_no">
                <el-select
                  v-model="props.row.batch_no"
                  style="width: 240px"
                  :disabled="props.row.productDisabled"
                >
                  <el-option
                    v-for="item in props.row.stock_batch"
                    :key="item.batch_no"
                    :label="item.batch_no"
                    :value="item.batch_no"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column prop="price" align="center" width="170">
            <template #header>
              <span class="required_text">*</span>
              <span>价格</span>
            </template>
            <template #default="props">
              <el-form-item prop="price">
                <el-input-number
                  :min="0"
                  :precision="2"
                  :controls="false"
                  class="width_100"
                  placeholder="价格不可低于底价"
                  v-model.trim="props.row.price"
                  :disabled="props.row.priceDisabled"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="unit_name" align="center" width="150">
            <template #header>
              <span class="required_text">*</span>
              <span>计价单位</span>
            </template>
            <template #default="props">
              <span class="ellipsis">
                {{ props.row.unit_name || '--' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="down_price" align="center" width="100">
            <template #header>
              <span class="required_text">*</span>
              <span>底价</span>
            </template>
            <template #default="props">
              {{ _FieldFormat(props.row.down_price, 'money', 2) }}
            </template>
          </el-table-column>
          <el-table-column prop="row_audit_status_str" align="center" width="100">
            <template #header>
              <span>行审核状态</span>
            </template>
            <template #default="props">
              {{ props.row.row_audit_status_str || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="forbid_status" align="center" width="100">
            <template #header>
              <span class="required_text">*</span>
              <span>生效状态</span>
            </template>
            <template #default="props">
              <el-tag  class="ml-2" :type="forbidStatusColor(props.row.forbid_status_str)">{{ props.row.forbid_status_str || '--' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="effective_date" align="center" width="220">
            <template #header>
              <span>生效日期</span>
            </template>
            <template #default="props">
              <VabTimeForm class="width_100" type="datetime" :disabled="props.row.productDisabled" v-model="props.row.effective_date" :disabledDateFun="disabledDateFun"/>
            </template>
          </el-table-column>
          <el-table-column prop="expiry_date" align="center" width="220">
            <template #header>
              <span>失效日期</span>
            </template>
            <template #default="props">
              <VabTimeForm class="width_100" type="datetime" :disabled="props.row.productDisabled" v-model="props.row.expiry_date" :disabledDateFun="disabledDateFun"/>
            </template>
          </el-table-column>
          <el-table-column prop="forbider_name" align="center" width="100">
            <template #header>
              <span>失效人员</span>
            </template> 
            <template #default="props">
              {{ props.row.forbider_name || '--' }}
            </template>
          </el-table-column>
          
          <el-table-column fixed="right" label="操作" width="60">
            <template #header>
              <span class="text_center">操作</span>
            </template>
            <template #default="props">
              <div class="flex_column_center">
                <vab-icon
                  v-if="!props.row.row_audit_status"
                  icon="delete-bin-5-line"
                  @click="handleRemove(props.$index)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <ProductsAll ref="productsAllRef" />
  </vab-card>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ProductsInformation',
})

/**
 * @props
 */
defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
  isWarn: {
    type: Boolean,
    default: false,
  }
})
/**
 * @import
 */
import { ref } from 'vue'
import ProductsAll from './ProductsAll.vue'
import { DateFormat, FieldFormat } from '/@/utils/utils'
import { getProductList } from '/@/api/dms/product'
import { ElMessage, FormRules } from 'element-plus'
import LazySelect from '/@/components/lazySelect/index.vue'
import { forbidStatusColor } from './tools';
/**
 * @var
 */
const tableLoading = ref(false)
const proxy: any = getCurrentInstance()?.proxy

const productFormRef = ref()
const productsAllRef = ref<any>(null)
const lazySelectNumberRef = ref()

// 基础五个数据
const productList = ref<any>([])
const userOrgId = ref('') //使用组织id
const currentRow = ref<any>() //选中块
// 详情基础信息
let detailBaseInfo = reactive<any>(null)

interface RuleForm {
  name: string
  number: string
  price: string | number
}

const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  number: [{ required: true, message: '产品编码不能为空', trigger: 'blur' }],
})
/**
 * @method
 */
const emit = defineEmits(['checkUseOrg'])

// 单选
const handleCurrentChange = (row: any) => {
  currentRow.value = row
}

// 根据获取到的截止日期，设置起始日期选择范围
const disabledDateFun = (time: Record<string, any>): boolean => {
  if (time.getTime() > new Date(detailBaseInfo.expiry_date).getTime()) {
    return true;
  } else {
    return false;
  }
}
// 字段格式化
const _FieldFormat = (value: string, type = '', radio = 2) => {
  return FieldFormat(value, type, radio)
}
// 校验使用组织是否选择
const LazyFocus = () => {
  emit('checkUseOrg')
}
// 删除
const handleRemove = (index: number) => {
  productList.value.splice(index, 1)
}
// 操作产品价格
const handleProduct = async (value = '') => {
  // 新增
  if (value == 'add') {
    productList.value.unshift({
      forbid_status: 0,
      down_price: 0,
      price: '',
      expiry_date: detailBaseInfo.expiry_date,
      effective_date: detailBaseInfo.effective_date,
      colorRow: 'add-row'
    })
    return
  }
  if (!currentRow.value) {
    ElMessage({ type: 'warning', message: '请选择需要操作的产品！' })
    return
  }

  // 价格更新
  if (value == 'priceUpdate') {
    productList.value.forEach((item: any) => {
      currentRow.value.forEach((jtem: any) => {
        if (item.id == jtem.id) {
          item.priceDisabled = false
          item.colorRow = 'modify-row'
        }
      })
    });
  }
  // 停用
  if (value == 'stop') {
    await productList.value.forEach((item: any) => {
      currentRow.value.forEach((jtem: any) => {
        if (item.id == jtem.id) {
          item.status = 1
          item.forbid_status_str = ''
          item.row_audit_status_str = '已停用'
        }
      })
    });
  }
  // 启用
  if (value == 'start') {
    productList.value.forEach((item: any) => {
      currentRow.value.forEach((jtem: any) => {
        if (item.id == jtem.id) item.forbid_status = 0
      })
    });
  }
}

// 产品价格带出基本信息
const productQuerySearch = async (value: string | number, type = '', index = 0, lay = 'number') => {

  const res = await getProductList({
    page: 1,
    limit: 2000,
    type: 1,
    filter: { number: type == 'number' ? value : '', name: type == 'name' ? value : '' },
  })

  const row = res.data.list[0]

  // 判断产品名称不能选中，来回切换报警
  if (lay == 'name') {
    if (productList.value[index].number == value) {
      productList.value[index].name = row.name
      return
    }
  }


  if (productList.value.length > 1) {

    let voidNumber = false
    voidNumber = productList.value.some((item: any) => item.number == row.number && item.row_audit_status_str != '已停用')

    if (voidNumber) {
      proxy.$Message('编码重复,请重新选择！', 'warning')
      productList.value[index] = {
        down_price: 0,
        base_price: 0,
      }
      return
    }
  }

  productList.value[index] = {
    ...row,
    price: '',
    down_price: row.base_price,
    forbid_status: 0,
    product_id: row.id,
    product_name: row.name,
    product_number: row.number,
    stock_batch: row.stock_batch,
    expiry_date: detailBaseInfo.expiry_date,
    effective_date: detailBaseInfo.effective_date,
    batch_no: '',
    id: 0,
  }
}


// 重置数据
const resetData = (value: any) => {
  userOrgId.value = value
}

const getScreen = async () => { }

// 获取更新数据
const getUpdateData = (res: any) => {
  tableLoading.value = true

  detailBaseInfo = res

  productList.value = []
  productList.value = res.product.map((item: any) => {
    return {
      ...item,
      priceDisabled: true,
      productDisabled: true,
      base_price: item.down_price || 0
    }
  })
  tableLoading.value = false
}

// 多选框禁用
const selectable = (row: any, i: number) => {
  if (row.status == 0 && row.row_audit_status == 1) return false
  if (row.status > 1) return false
  return true
}

// 自定义颜色块
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  if (row.colorRow) return row.colorRow
  return ''
}

/**
 * @实例
 */
//抛出数据
defineExpose({
  productFormRef,
  productList,
  getScreen,
  resetData,
  getUpdateData,
})
onMounted(() => {
  getScreen()
})
</script>

<style lang="scss" scoped>
:deep() {
  .el-loading-spinner {
    display: none;
  }
}

.products_font1 {
  font-size: 16px;
  margin-bottom: 15px;
}

.products_div {
  width: 300px;
}

.products_div1 {
  margin-right: 20px;
  margin-left: 10px;
  display: inline-block;

  :deep() {
    .el-input__wrapper {
      border-bottom-right-radius: 0px !important;
      border-top-right-radius: 0px !important;
      border-right: 0px solid !important;
    }

    .el-button {
      border-bottom-left-radius: 0px !important;
      border-top-left-radius: 0px !important;
      border-left: 0px solid !important;
    }
  }
}

.products_font2 {
  color: rgb(245, 154, 35);
  margin-left: 20px;
}

.products_div2 {
  margin-right: 20px;
}

.products_div3 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 25px;
  margin-top: 25px;
}

.formData {
  :deep() {
    .el-form-item {
      margin-bottom: 0px;
    }
  }

  .icon_color {
    color: #0967f4;
    margin-right: 4px;
  }
}

.warn {
  border: 2px dashed red;
}


:deep() {

  // 新增
  .el-table .add-row {
    --el-table-tr-bg-color: rgba(255, 69, 0, 0.6);
  }

  // 修改
  .el-table .modify-row {
    --el-table-tr-bg-color: rgba(255, 165, 0, 0.6);
  }

  .el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
  }
}
</style>
